<template>
  <div style="overflow: auto; height: 100%">
    <div
      style="height: 100%; display: flex; align-items: center"
      v-if="treeData.length === 0"
    >
      <a-empty :image="notData">
        <template #description>
          <span style="color: rgba(0, 0, 0, 0.25)"> 暂无数据 </span>
        </template>
      </a-empty>
    </div>

    <template v-else>
      <div class="loading" v-if="loading">
        <a-spin :spinning="loading" />
      </div>
      <!-- defaultExpandAll -->

      <a-tree
        v-else
        class="tree"
        :selectedKeys="selected"
        v-model:expanded-keys="expandedKeys"
        :blockNode="true"
        :show-line="{ showLeafIcon: false }"
        :tree-data="treeData"
        :fieldNames="{ key: 'id', title: 'fileName' }"
        :showIcon="false"
        :load-data="onLoadData"
      >
        <template #switcherIcon="{ switcherCls }">
          <down-outlined :class="switcherCls" />
        </template>
        <template #title="item">
          <div
            class="title"
            :class="{
              active: selected.includes(item.id),
            }"
            @click="onClick(item)"
          >
            <div
              style="
                display: flex;
                justify-content: space-between;
                align-items: center;
              "
            >
              <div>
                {{ item.fileName }}
              </div>
              <button-more
                :data="item"
                @delete="onDelete(item)"
                v-if="item.myRoot"
              />
            </div>
          </div>
        </template> </a-tree
    ></template>
  </div>
</template>
<script setup>
import { useVModel } from '@vueuse/core'
import { DownOutlined } from '@ant-design/icons-vue'
import ButtonMore from './tree-aside-more.vue'
import { queryPrjInfo, queryPrjTree } from '@/api/db.js'
import { onMounted, ref } from 'vue'
import notData from '@/assets/images/not-data.png'
import { useDbType } from './provide-context.js'
import { useRoute } from 'vue-router'
/**
 * 外部参数
 */
let props = defineProps({
  selected: { type: Array, default: () => [] },
})
/**
 * 事件定义
 */
let emit = defineEmits(['update:selectedInfo', 'ready'])
/**
 * 双向绑定
 */
let selectedInfo = useVModel(props, 'selectedInfo', emit)
let treeData = ref([])
let selected = ref([])
let expandedKeys = ref([])
/**
 * 选中详情
 */
function onClick(item) {
  // if ((item?.children || [])?.length === 0) {
  selectedInfo.value = item
  selected.value = [item.id]
  // }
}
/**
 * 数据初始化
 */
let loading = ref(false)
let dbType = useDbType()
let route = useRoute()
async function update() {
  loading.value = true
  try {
    let categoryName = decodeURIComponent(route.query.categoryName)
    let result = await queryPrjInfo({}, dbType)
    treeData.value = (result?.data?.records || []).map(item => ({
      ...item,
      myRoot: true,
    }))

    if (route.query.categoryName) {
      treeData.value = treeData.value.filter(
        item => item.fileName === categoryName,
      )
    }

    emit('ready', treeData.value)
  } catch (e) {
    console.log(e)
  }
  loading.value = false
}
onMounted(update)

/**
 * 加载子树
 */
async function onLoadData(treeNode) {
  if (treeNode.dataRef.myRoot && !treeNode.dataRef.children) {
    let result = await queryPrjTree({ prjId: treeNode.dataRef.id })
    let children = result?.data?.children || []
    standardizationData(children)
    treeNode.dataRef.children = children
    treeData.value = [...treeData.value]
  }
}

function standardizationData(nodes) {
  nodes.forEach(node => {
    if (node.children instanceof Array) {
      standardizationData(node.children)
    } else {
      node.isLeaf = true
    }
  })
}

/**
 * 删除
 */
function onDelete(item) {
  // if (
  //   item.id &&
  //   selected.value[0] &&
  //   item.id === selected.value[0]
  // ) {
  selectedInfo.value = undefined
  selected.value = []

  treeData.value = treeData.value.filter(({ id }) => {
    return id !== item.id
  })

  // }
  // update()
}
</script>
<style lang="less" scoped>
// .ant-tree {
//   background-color: red;
//   .ant-tree-switcher-noop {
//     display: none;
//   }
//   .ant-tree-node-selected {
//     color: #0086ff;
//     background-color: #fff;
//   }
// }
.tree {
  .title {
    position: relative;
    color: #000;
    &.active {
      color: #3d6d99;
      &::after {
        content: ' ';
        position: absolute;
        right: -36px;
        width: 0;
        height: 0;
        border-right: 12px solid #fff;
        border-top: 12px solid transparent;
        border-bottom: 12px solid transparent;
        pointer-events: none;
      }
    }
  }
}
:deep(.ant-tree.ant-tree-directory .ant-tree-treenode-selected:hover::before),
:deep(.ant-tree.ant-tree-directory .ant-tree-treenode-selected::before) {
  background-color: white;
}

:deep(.ant-tree.ant-tree-directory)
  .ant-tree-treenode-selected
  .ant-tree-switcher {
  color: #000;
}
.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>
